﻿using FlaUI.UIA3;
using System.Diagnostics;
using System;
using System.IO;
using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using System.Linq;
using FlaUI.Core.Definitions;

public class WXWork5Automation
{
    private Window _mainWindow;

    public bool Initialize()
    {
        try
        {
            System.Threading.Thread.Sleep(8000); // 5.0版本启动较慢

            var processes = Process.GetProcessesByName("WXWork");
            if (processes.Length == 0)
            {
                // 企业微信 5.0 常见安装路径
                string[] paths = {
                    @"D:\Program Files (x86)\WXWork\WXWork.exe",
                    Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\AppData\Local\Programs\WXWork\WXWork.exe")
                };

                foreach (var path in paths)
                {
                    if (File.Exists(path))
                    {
                        var app = Application.Launch(path);
                        System.Threading.Thread.Sleep(8000); // 5.0版本启动较慢
                        break;
                    }
                }
            }

            processes = Process.GetProcessesByName("WXWork");
            if (processes.Length > 0)
            {
                var app = Application.Attach(processes[0]);
                using (var automation = new UIA3Automation())
                {
                    _mainWindow = app.GetMainWindow(automation);
                    return _mainWindow != null;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"初始化失败: {ex.Message}");
        }
        return false;
    }

    public void ExploreWXWork5Structure()
    {
        Console.WriteLine("=== 企业微信 5.0.0.8611 UI结构探索 ===");

        // 1. 查找所有自定义控件
        var customControls = _mainWindow.FindAllDescendants(cf => cf.ByControlType(ControlType.Custom));
        Console.WriteLine($"自定义控件: {customControls.Length}");

        // 2. 查找特定类名的元素（企业微信5.0常用类名）
        var allElements = _mainWindow.FindAllDescendants();
        var wxClasses = allElements.Where(e =>
            !string.IsNullOrEmpty(e.ClassName) &&
            (e.ClassName.Contains("WX") ||
             e.ClassName.Contains("WeChat") ||
             e.ClassName.Contains("TX") ||
             e.ClassName.Contains("RichEdit") ||
             e.ClassName.StartsWith("Afx:")))
            .ToList();

        Console.WriteLine($"企业微信相关类名: {wxClasses.Count}");
        foreach (var element in wxClasses.Take(10))
        {
            var bounds = element.BoundingRectangle;
            Console.WriteLine($"  {element.ClassName} - 位置: ({bounds.Left}, {bounds.Top})");
        }
    }
}